package com.cuijian.demo.controller;

import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.cuijian.demo.common.JsonResult;
import com.cuijian.demo.model.User;
import com.cuijian.demo.util.PasswordUtil;
import com.cuijian.demo.util.TokenManager;
import com.cuijian.demo.util.JsonUtil;
import com.cuijian.demo.dto.UserUpdateRequest;
import com.cuijian.demo.dto.ChangePasswordRequest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Path("/api/user")
public class UserController extends Controller {

    /**
     * 修改用户信息 - 支持JSON和表单格式
     */
    public void updateProfile() {
        // 验证token
        if (!verifyToken()) {
            renderJson(JsonResult.error("未授权访问").toMap());
            return;
        }

        TokenManager.TokenInfo tokenInfo = getTokenInfo();
        if (tokenInfo == null) {
            renderJson(JsonResult.error("token无效").toMap());
            return;
        }

        Long userId = tokenInfo.getUserId();
        String email;
        String phone;
        String realName;
        String avatar;

        // 检查是否为JSON请求
        if (JsonUtil.isJsonRequest(this)) {
            UserUpdateRequest updateRequest = JsonUtil.getJsonData(this, UserUpdateRequest.class);
            if (updateRequest == null) {
                renderJson(JsonResult.error("请求数据不能为空").toMap());
                return;
            }
            email = updateRequest.getEmail();
            phone = updateRequest.getPhone();
            realName = updateRequest.getRealName();
            avatar = updateRequest.getAvatar();
        } else {
            // 表单格式
            email = get("email");
            phone = get("phone");
            realName = get("realName");
            avatar = get("avatar");
        }

        try {
            User user = User.dao.findById(userId);
            if (user == null) {
                renderJson(JsonResult.error("用户不存在").toMap());
                return;
            }

            // 更新字段
            if (email != null) {
                // 检查邮箱是否被其他用户使用
                User existUser = User.dao.findByEmail(email);
                if (existUser != null && !existUser.getId().equals(userId)) {
                    renderJson(JsonResult.error("邮箱已被其他用户使用").toMap());
                    return;
                }
                user.set("email", email);
            }

            if (phone != null) user.set("phone", phone);
            if (realName != null) user.set("real_name", realName);
            if (avatar != null) user.set("avatar", avatar);
            user.set("update_time", new Date());

            boolean success = user.update();
            if (success) {
                renderJson(JsonResult.success("个人信息更新成功").toMap());
            } else {
                renderJson(JsonResult.error("个人信息更新失败").toMap());
            }

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("更新失败: " + e.getMessage()).toMap());
        }
    }

    /**
     * 修改密码 - 支持JSON和表单格式
     */
    public void changePassword() {
        // 验证token
        if (!verifyToken()) {
            renderJson(JsonResult.error("未授权访问").toMap());
            return;
        }

        TokenManager.TokenInfo tokenInfo = getTokenInfo();
        if (tokenInfo == null) {
            renderJson(JsonResult.error("token无效").toMap());
            return;
        }

        Long userId = tokenInfo.getUserId();
        String oldPassword;
        String newPassword;

        // 检查是否为JSON请求
        if (JsonUtil.isJsonRequest(this)) {
            ChangePasswordRequest passwordRequest = JsonUtil.getJsonData(this, ChangePasswordRequest.class);
            if (passwordRequest == null) {
                renderJson(JsonResult.error("请求数据不能为空").toMap());
                return;
            }
            oldPassword = passwordRequest.getOldPassword();
            newPassword = passwordRequest.getNewPassword();
        } else {
            // 表单格式
            oldPassword = get("oldPassword");
            newPassword = get("newPassword");
        }

        if (oldPassword == null || oldPassword.trim().isEmpty()) {
            renderJson(JsonResult.error("原密码不能为空").toMap());
            return;
        }

        if (newPassword == null || newPassword.trim().isEmpty()) {
            renderJson(JsonResult.error("新密码不能为空").toMap());
            return;
        }

        if (newPassword.length() < 6) {
            renderJson(JsonResult.error("新密码长度不能少于6位").toMap());
            return;
        }

        try {
            User user = User.dao.findById(userId);
            if (user == null) {
                renderJson(JsonResult.error("用户不存在").toMap());
                return;
            }

            // 验证原密码
            if (!PasswordUtil.verify(oldPassword, user.getPassword())) {
                renderJson(JsonResult.error("原密码错误").toMap());
                return;
            }

            // 更新密码
            user.set("password", PasswordUtil.md5(newPassword));
            user.set("update_time", new Date());

            boolean success = user.update();
            if (success) {
                // 密码修改成功后，使当前token失效
                String token = getHeader("Authorization").substring(7);
                TokenManager.removeToken(token);

                renderJson(JsonResult.success("密码修改成功，请重新登录").toMap());
            } else {
                renderJson(JsonResult.error("密码修改失败").toMap());
            }

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("密码修改失败: " + e.getMessage()).toMap());
        }
    }

    // 其他方法保持不变...
    private boolean verifyToken() {
        String authHeader = getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return false;
        }

        String token = authHeader.substring(7);
        return TokenManager.verifyToken(token);
    }

    private TokenManager.TokenInfo getTokenInfo() {
        String authHeader = getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return null;
        }

        String token = authHeader.substring(7);
        return TokenManager.getTokenInfo(token);
    }
}